//
//  MainViewController.m
//  PhotoBase
//
//  Created by Alec Flett on 11/16/09.
//  Copyright __MyCompanyName__ 2009. All rights reserved.
//

#import "MainViewController.h"
#import "MainView.h"
#import "CocoaTouch/FreebaseSuggest.h"
#import "JSON/JSON.h"

@implementation MainViewController
@synthesize photoButton = _photoButton;
@synthesize currentImage = _currentImage;
@synthesize topicButton = _topicButton;
@synthesize progressView = _progressView;
@synthesize progressLabel = _progressLabel;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}


- (void)dealloc {
    [super dealloc];
}



 // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
 - (void)viewDidLoad {
     [super viewDidLoad];

     if (self.image)
         self.currentImage.image = self.image;
     NSLog(@"viewDidLoad");
 }

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
    [super viewDidUnload];
    NSLog(@"viewDidUnload");
    self.currentImage = nil;
    self.photoButton = nil;
    self.topicButton = nil;
    
    //
    [self.progressView removeFromSuperview];
    self.progressView = nil;
    self.progressLabel = nil;
}



/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */


- (void)flipsideViewControllerDidFinish:(FlipsideViewController *)controller {
    
	[self dismissModalViewControllerAnimated:YES];
}

- (IBAction)startChoosePicture {
    
    UIActionSheet* pictureChooser = [[UIActionSheet alloc] 
                                     initWithTitle:@"Take a picture"
                                     delegate:self 
                                     cancelButtonTitle:@"Cancel" 
                                     destructiveButtonTitle:nil
                                     otherButtonTitles:
                                     @"Choose a picture",
                                     @"Take a Picture", nil];
    [pictureChooser showInView:self.view];
    [pictureChooser release];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == actionSheet.cancelButtonIndex)
        return;
    
    if (buttonIndex == 0)
        [self usePicture:UIImagePickerControllerSourceTypePhotoLibrary];
    else if (buttonIndex == 1)
        [self usePicture:UIImagePickerControllerSourceTypeCamera];    

    else
        NSLog(@"ActionSheet unknown index %d", buttonIndex);
}
    
- (void)usePicture:(UIImagePickerControllerSourceType)sourceType {
    NSLog(@"Taking a picture....");
    if (![UIImagePickerController isSourceTypeAvailable:sourceType])
        return;
    
    NSLog(@"Using source type %d", sourceType);
    UIImagePickerController* picker = [[UIImagePickerController alloc] init];
    picker.sourceType = sourceType;
    picker.allowsEditing = YES;
    picker.delegate = self;
    
    [self presentModalViewController:picker animated:YES];
    [picker release];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSLog(@"didFinsihPickingMediaWithInfo: %@", info);
    UIImage* image = [info objectForKey:UIImagePickerControllerEditedImage];
    if (!image)
        image = [info objectForKey:UIImagePickerControllerOriginalImage];
    [self useImage:image];
    
    [self.photoButton setTitle:nil forState:UIControlStateNormal];
    
    // Remove the picker interface and release the picker object.
    [[picker parentViewController] dismissModalViewControllerAnimated:YES];
}

- (UIImage*)image {
    return _image;
}

- (void)setImage:(UIImage*)image
{
    if (_currentImage) {
        
        NSLog(@"Attaching image");
        _currentImage.image = image;        
    }
    [_image release];
    _image = [image retain];
}

- (NSDictionary*)topic
{
    return _topic;
}

- (void)setTopic:(NSDictionary*)topic
{
    _topic = [topic retain];
    id topicId = [topic objectForKey:@"id"];
    NSString* title;
    if (topicId && topicId != [NSNull null])
        title = [NSString stringWithFormat:@"Uploading to \"%@\"...",
                 [topic objectForKey:@"name"]];
    else
        title = [NSString stringWithFormat:@"Creating \"%@\"...",
                 [topic objectForKey:@"name"]];
    [_topicButton setTitle:title forState:UIControlStateNormal];        
}

- (void)useImage:(UIImage*)image
{
    self.image = image;
}

- (void)errorDidOccur:(id)result request: (id<FreebaseRequest>) request
{
    _progressView.hidden = YES;
    NSLog(@"MainViewController error in %@: %@", request.name, result);
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Upload Error" 
                                                    message:[NSString stringWithFormat: [result description]]
                                                   delegate:self 
                                          cancelButtonTitle:@"Sign in..." 
                                          otherButtonTitles:nil];
    [alert show];
    [alert release];
}

- (IBAction)chooseTopic {
    FreebaseSuggest* controller = [[FreebaseSuggest alloc] init];
    
    controller.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    controller.delegate = self;
    controller.allowCreateNew = YES;
    NSLog(@"AllowCreateNew? %d", controller.allowCreateNew);
    NSLog(@"  what about in %@? %d", controller.search, controller.search.allowCreateNew);
    
    NSArray *mql_filter = [NSArray arrayWithObject:
                           [NSDictionary dictionaryWithObjectsAndKeys:
                            [NSDictionary dictionaryWithObjectsAndKeys:
                             @"forbidden", @"optional",
                             [NSArray arrayWithObjects:@"/location/country",
                              @"/location/us_state", @"/location/continent", 
                              @"/location/us_county", nil], @"id|=",
                             nil],
                            @"type",
                            nil]];
    controller.mqlFilter = [mql_filter JSONRepresentation];
    
    [self presentModalViewController:controller animated:YES];
    [controller release];
}

-(void)suggest:(FreebaseSuggest*)suggest itemSelected:(NSDictionary*)itemSelected
{
    [self dismissModalViewControllerAnimated:YES];
    if (!itemSelected)
        return;
    
    NSLog(@"Picked a topic: %@", itemSelected);
    self.topic = itemSelected;
}

    

- (IBAction)showInfo {    
	
	FlipsideViewController *controller = [[FlipsideViewController alloc] initWithNibName:@"FlipsideView" bundle:nil];
	controller.delegate = self;
	
	controller.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    
	[self presentModalViewController:controller animated:YES];
	[controller release];
}


- (IBAction)upload {
 
    // noop if no image
    if (!self.image || !_topic)
        return;
        
    [self showProgress:@"Logging in"];
    
    NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
    FreebaseSession* session = [FreebaseSession session];
    
    NSString *username = [defaults stringForKey:@"freebase.username"];
    NSString *password = [defaults stringForKey:@"freebase.password"];
    
    if (!username || [username length] == 0 ||
        !password || [password length] == 0) {
        
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Login" message:@"No username or password provided"
                                                       delegate:self
                                              cancelButtonTitle:nil
                                              otherButtonTitles:nil];
        [alert show];
        [alert release];
        return;
    }
    
    // shouldn't Freebase.framework handle this?
    if ([defaults boolForKey:@"freebase.use_sandbox"])
        session.hostname = @"api.sandbox-freebase.com";
    else
        session.hostname = @"api.freebase.com";
    
    
    [session login:username
          password:password
          delegate:self
 didFinishSelector:@selector(uploadLoggedIn)];
}

- (void)topicCreated:(NSDictionary*)newTopic
{
    self.topic = newTopic;
    [self uploadLoggedIn];
}

- (void)uploadLoggedIn
{
    if ([[self.topic objectForKey:@"create"] isEqualToString:@"unconditional"]) {
        [[FreebaseSession session] mqlwrite:self.topic
                                       name:@"topic_create"
                                   delegate:self 
                          didFinishSelector:@selector(topicCreated:)];
        return;
    }
    [self showProgress:@"Uploading image..."];
    [[FreebaseSession session] uploadImage:self.image 
                               contentType:@"image/jpeg" 
                                     topic:[self.topic objectForKey:@"id"]
                                  delegate:self 
                         didFinishSelector:@selector(uploaded:) 
                                   options:
     [NSDictionary dictionaryWithObjectsAndKeys:
      @"/en/creative_commons_by_sa_2_0", @"license", nil]];
    
}

- (void)uploaded:(id)result
{
    [self hideProgress];
    NSLog(@"Uploaded: %@", result);
}

- (void)showProgress:(NSString*)message
{
    [self.view addSubview:_progressView];
    _progressView.hidden = NO;
    _progressLabel.text = message;
}

- (void)hideProgress
{
    _progressView.hidden = YES;
}


/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

// at the moment we assume this is the "you need a username/password"
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    [self showInfo];
}

@end
